package com.iocup.keybastion.core.matching.impl;

import com.iocup.keybastion.context.WebContextHolder;
import com.iocup.keybastion.core.matching.Matcher;
import com.iocup.keybastion.utils.PathUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 路由匹配器
 *
 * @author xyjxust
 * @create 2022/3/1 15:00
 **/
public class RouterMatcher implements Matcher {
    /**
     * 拦截路由
     */
    private List<String> includeList = new ArrayList<>();
    /**
     * 放行路由
     */
    private List<String> excludeList = new ArrayList<>();
    /**
     * 路径匹配工具
     */
    private PathUtil pathUtil = new PathUtil();


    /**
     * 添加 [拦截路由]
     *
     * @param paths 路由
     * @return 对象自身
     */
    public RouterMatcher addInclude(String... paths) {
        includeList.addAll(Arrays.asList(paths));
        return this;
    }

    /**
     * 添加 [放行路由]
     *
     * @param paths 路由
     * @return 对象自身
     */
    public RouterMatcher addExclude(String... paths) {
        excludeList.addAll(Arrays.asList(paths));
        return this;
    }


    @Override
    public boolean matches(WebContextHolder webContextHolder) {
        //获取请求路径
        String url = webContextHolder.getRequestURL();
        //如果拦截路由中没有地址或者地址本身在放行路由中
        if (CollectionUtils.isEmpty(includeList) || pathUtil.isMatch(excludeList, url)) {
            return true;
        }
        //不满足拦截路由
        if (!pathUtil.isMatch(includeList, url)) {
            return false;
        }
        return true;
    }
}
